import logging
from typing import Dict
from astro_info import *
from zodiac_info import *

from langchain_core.prompts import PromptTemplate
import os
from langchain_community.llms import Tongyi
from langchain_deepseek import ChatDeepSeek
from langchain_openai import ChatOpenAI
import astrofunctions as f
from langchain_ollama import ChatOllama
from datetime import datetime
import re
import pytz



def anwser(model_prod, model, birthday, question, chat_history):
    # timestamp_float = float(birthday)
    # dt_object = datetime.fromtimestamp(timestamp_float)
    # birthday = dt_object.strftime('%Y%m%d')
    birthday_check = True
    if len(birthday) != 8:
        birthday_check = False
    try:
        datetime.strptime(birthday, '%Y%m%d')
    except ValueError:
        birthday_check = False
    if birthday_check:
        llm_name = model_prod
        logging.info(f"llm_name: {model_prod}")
        logging.info(f"birthday: {birthday}")
        logging.info(f"question: {question}")
        os.environ["DASHSCOPE_API_KEY"] = "sk-1e4cc7fbb43643cf806e82191b0ca160"
        os.environ["DEEPSEEK_API_KEY"] = "sk-1908aed1c456433ca5d1abb22574cb62"
        SILICONFLOW_API_KEY = "sk-meosqmudzxwgifmudetqprzpkmyrmhqldplltusymdeugmue"
        match llm_name:
            case "tongyi":
                llm = Tongyi()
            case "deepseek":
                llm = ChatDeepSeek(
                                    model=model,
                                    temperature=0.5,
                                    max_tokens=None,
                                    timeout=None,
                                    max_retries=2
                                )
            case "siliconflow":
                llm = ChatOpenAI(
                    model=model,
                    temperature=0.5,
                    max_tokens=None,
                    timeout=None,
                    max_retries=2,
                    api_key=SILICONFLOW_API_KEY,
                    base_url="https://api.siliconflow.cn/v1",
                )
            case "ollama":
                llm = ChatOllama(model=model,
                                 temperature=0.5,
                                 base_url="http://julyperla.asuscomm.com:11434/")
                                 # base_url="http://localhost:11434/")

        #根据生日获取占星知识
        ##1.根据生日获取星座
        astro = f.birthday_to_astro(birthday)
        ##2.根据星座获取星座解读
        sense = f.astro_to_sense(astro)
        ##3.根据星座获取主宰行星
        ruling_planet = f.ruling_planet(astro)
        ##4.根据生日与主宰行星获取主宰行星当日所处的星座
        birthday_ruling_planet_astro = f.get_ruling_planet_birthday_astro(birthday, ruling_planet)
        #获取解读
        # logging.info(f"{ruling_planet.upper()}_{birthday_ruling_planet_astro.upper()}_SENSE")
        birthday_ruling_planet_astro_sense = globals().get(f"{ruling_planet.upper()}_{birthday_ruling_planet_astro.upper()}_SENSE", None)
        if birthday_ruling_planet_astro_sense is None:
            birthday_ruling_planet_astro_sense = "主宰行星生日当天未处于十二星座中，没有这部分解读"
        ##5.根据生日与主宰行星获取主宰行星当日所处的宫位
        birthday_ruling_planet_zodiac = f.get_ruling_planet_zodiac(ruling_planet_name=ruling_planet, birthday_str=birthday)
        # 获取解读
        # logging.info(f"{ruling_planet.upper()}_{birthday_ruling_planet_zodiac.upper()}_SENSE")
        birthday_ruling_planet_zodiac_sense = globals().get(f"{ruling_planet.upper()}_{birthday_ruling_planet_zodiac.upper()}_SENSE", None)
        ##6.根据主宰行星获取主宰行星现在时间所处的宫位
        now_ruling_planet_zodiac = f.get_ruling_planet_zodiac(ruling_planet_name=ruling_planet)
        #获取解读
        # logging.info(f"{now_ruling_planet_zodiac.upper()}_SENSE")
        now_ruling_planet_zodiac_sense = globals().get(f"{now_ruling_planet_zodiac.upper()}_SENSE", None)
        history = []
        for chat in chat_history:
            history.append(chat['role'] + ":" + chat['content'])
        #当前时间
        timezone = pytz.timezone('Asia/Shanghai')  # 根据需要更改时区
        dt = datetime.now(tz=timezone)
        dt_str = dt.strftime('%Y年%m月%d日 %H时%M分')
        template = f'''
## 聊天历史记录
-- **聊天历史记录**：{history}
## 用户当前问题
-- **用户当前问题**：{question}
## 定位
-- **占星术士**: 一个仔细阅读了占星上下文信息，回答来自于占星上下文信息，不会自己创造答案，回答用户问题精炼简短，围绕问题回答的占星术士
## 占星上下文信息
-- **主宰行星在我的生日所处的星座的解读**：{birthday_ruling_planet_astro_sense}
-- **主宰行星在我的生日所处的宫位**：{birthday_ruling_planet_zodiac}
-- **主宰行星在我的生日所处的宫位的解读**：{birthday_ruling_planet_zodiac_sense}
-- **我的星座解读**：{sense}
-- **主宰行星现在所处的宫位**：{now_ruling_planet_zodiac}
-- **主宰行星现在所处的宫位解读**：{now_ruling_planet_zodiac_sense}
-- **我的主宰行星**：{ruling_planet}
-- **我的生日**：{birthday}
-- **我的星座**：{f.translate_zodiac_to_chinese(astro)}
## 当前日期与时间
-- **年月日时分**：{dt_str}
## 使用示例
- **用户问题**：我是什么星座？
- **占星师回答**：你是水瓶座，生日1997年2月10日。
水瓶座象征自由与革新，主宰行星天王星赋予你独立、前瞻的思维，重视平等与群体进步。内在可能藏有反叛与突破传统的渴望，但外在常显理性抽离。✨
有具体问题可以继续提问～
- **用户问题**：我现在运势如何？
- **占星师回答**：根据星象，天王星正行经你的第二宫（财富宫），近期财务或价值观可能有突发变化。水瓶座独立创新的特质被激活，适合突破传统收入模式，尝试数字化、科技相关机会。但需注意第十二宫隐藏的惯性束缚——内心渴望自由却因现实顾虑停滞，可能突然对现有经济结构产生反叛情绪。建议：用理性梳理财务计划的同时，留出20%空间接纳非常规机遇，警惕冲动消费。人际关系上可能出现价值观冲突，保持抽离视角更易化解。
有具体问题可以继续提问～
        '''
        logging.info(template)

        prompt = PromptTemplate.from_template(template)
        chain = prompt | llm

        # output = chain.invoke({"question": question})
        response = ""
        output_started = False
        if model_prod != "ollama" or model != "qwen3:30b-a3b-q8_0":
            output_started = True
        for chunk in chain.stream({"question": question}):
            print(chunk.content, end="", flush=True)
            if chunk.content == '</think>':
                output_started = True
                continue
            if output_started:
                response += chunk.content

                # 更新聊天历史
                updated_chat_history = chat_history.copy()
                new_message = {"role": "user", "content": question}
                updated_chat_history.append(new_message)

                assistant_message = {"role": "assistant", "content": response}
                updated_chat_history.append(assistant_message)

                yield "", updated_chat_history  # 清空问题输入框并更新聊天历史
        logging.info(response)
    else:
        new_message = {"role": "user", "content": question}
        assistant_message = {"role": "assistant", "content": "请输入正确的生日日期，格式参考:19970210"}
        chat_history.append(new_message)
        chat_history.append(assistant_message)
        yield "", chat_history
